package login

import (
	"crypto/md5"
	"crypto/sha1"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	AdminModel "jy_go/app/admin/model/admin"
	"jy_go/app/admin/model/admin_login_log"
	Config "jy_go/config"
	"jy_go/db"
	"jy_go/jwt"
	"jy_go/jy_log"
	"net/http"
)

var (
	Db = db.GetDb()
)


// 定义接收数据的结构体
type Data struct {
	// binding:"required"修饰的字段,声明客户端传过来的这个字段不允许为空，若接收为空值，则报错，是必须字段
	UserName string `form:"username" json:"username" xml:"username" binding:"required"`
	PassWord string `form:"password" json:"password" xml:"password" binding:"required"`
}

// @Summary 后台登录接口
// @Description 后台登录接口
// @Tags 登录
// @Accept mpfd
// @Param username query string true "用户名"
// @Param password query string true "密码"
// @Success 200 {string} string "{"message": "登录成功","code":"success","token":"abc"}"
// @Failure 400 {string} string "{"message": "登录失败","code":"error"}"
// @Router /admin/login [post]
func Login(c *gin.Context) {

	// 声明接收的变量
	var form Data
	// Bind()默认解析并绑定form格式
	// 根据请求头中content-type自动推断
	if err := c.Bind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "账号密码不能为空","code":"error"})
		return
	}

	//初始化结构体
	var admin AdminModel.Admin

	if err := Db.Select([]string{"id","username", "password","type","has"}).Where("username = ?",form.UserName).First(&admin).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			//查询为空
			c.JSON(http.StatusBadRequest, gin.H{"message": "账号不存在","code":"error"})
			return
		}
	}

	if admin.Type != 1 {
		c.JSON(http.StatusBadRequest, gin.H{"message":"账号已被禁用","code":"error"})
		return
	}

	//md5加密
	form.PassWord = fmt.Sprintf("%x", md5.Sum([]byte(form.PassWord)))
	//sha1加密
	form.PassWord = fmt.Sprintf("%x", sha1.Sum([]byte(form.PassWord + admin.Has)))

	// 判断用户名密码是否正确
	if form.PassWord != admin.Password {
		c.JSON(http.StatusBadRequest, gin.H{"message": "密码错误","code":"error"})
		return
	}

	//生成token并返回
	token,err := jwt.GetToken(admin.ID,[]byte(Config.Config("config","jwt","admin_jwt_key")))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message":"token生成失败","code":"error"})
		return
	}

	if err := Db.Create(&admin_login_log.AdminLoginLog{AdminId: admin.ID,IP: c.ClientIP()}).Error; err != nil {
		go jy_log.JyLog("后台登录日志添加失败，err：" + err.Error())
	}

	c.JSON(http.StatusOK, gin.H{"token": token,"message":"登录成功","code":"success"})
	return
}



